package lumis.content.source.filter;

import java.util.Locale;

import lumis.content.ContentManagerFactory;
import lumis.content.metadata.MetaDataConfig;
import lumis.doui.table.filter.TableSourceFilter;
import lumis.portal.PortalException;
import lumis.util.query.*;

import org.w3c.dom.Node;

/**
 * Generates a filter where the associated field must be equals to a 
 * metadata id.
 * <p>
 * The metadata id used is obtained by this filter using its associated value
 * as an itemId and searching for its corresponding metadata id.
 * @since 4.0.6
 * @version $Revision: 9601 $ $Date: 2008-07-18 15:38:17 -0300 (Fri, 18 Jul 2008) $
 * 
 * @deprecated Since 4.2.0, due to changes in 
 * {@link lumis.content.core content} storage structure.
 */
@Deprecated
public class MetaDataSourceFilter extends TableSourceFilter
{
	/**
	 * Always return the equals operator, just to be 
	 * a valid binary operator and the extended {@link TableSourceFilter}
	 * to behave as expected.
	 * @since 4.0.6
	 */
	@Override
	protected String calculateFilterOperator(Node filterNode) throws PortalException
	{
		return IQueryFilter.FILTER_OPERATOR_EQUAL;
	}

	/**
	 * Generate a query filter that filters the queryField by the metadata related to the given value (itemId request parameter).
	 * @param queryField the query field that will be filtered.
	 * @param queryValue the query value. Must be the itemId value for a content.
	 * @return the query filter.
	 */
	@Override
	public IQueryFilter getQueryFilter(QueryField queryField, IQueryValue queryValue) throws PortalException
	{
		String itemIdValue = (String)((QueryValue)queryValue).getValue();
		String metaDataIdValue = null;
		if (itemIdValue != null)
		{
			Locale userLocale = getSource().getSourceContext().getSessionConfig().getLocale();
			for (MetaDataConfig metaDataConfig : ContentManagerFactory.getMetaDataManager().getByItemId(getSource().getDouiContext().getRequest().getSessionConfig(), itemIdValue, getSource().getTransaction()))
			{
				// metaDataConfig associated to content's service instance, not 'published to' instances
				if (metaDataConfig.getParentServiceInstanceId() == null && (metaDataConfig.getLanguageId() == null || userLocale.toString().equals(metaDataConfig.getLanguageId()))) 
					metaDataIdValue = metaDataConfig.getId();
			}
		}
		return super.getQueryFilter(queryField, new QueryValue(metaDataIdValue));
	}
}
